# -*- coding: utf-8 -*-
# @Time    : 2020/6/7 18:09
# @Author  : Leeli
# @Email   : lililove2000@163.com
# @File    : main.py
# @Software: PyCharm

from time import strftime  # 导入time的strftime模块

from kivy.app import App  # 导入Kivy的App基类
from kivy.uix.boxlayout import BoxLayout  # 引入布局
from kivy.clock import Clock


# 布局类
class ClockBoxLayout(BoxLayout):
    # 初始化
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.timing_flag = False
        self.timing_second = 0
        self.on_start()

    # 每0秒执行一次update_time()方法
    def on_start(self):
        Clock.schedule_interval(self.update_time, 0)

    def update_time(self, nap):
        if self.timing_flag:
            self.timing_second = self.timing_second + nap
            # 通过id获取time_label_id控件设置text属性
        self.ids.time_label_id.text = strftime("[b]%H[/b]:%M:%S")
        m, s = divmod(self.timing_second, 60)
        # 通过id获取stopwatch控件设置text属性
        self.ids.stopwatch.text = ("%02d:%02d.[size=40]%02d[/size]" % (int(m), int(s), int(s * 100 % 100)))

    def start_or_stop(self):
        # 切换按钮状态
        """
        if self.timing_flag:
            self.ids.start_stop_button_id.text = "Start"
        else:
            self.ids.start_stop_button_id.text = "Stop"
        代码简写为
        self.ids.start_stop_button_id.text = "Start" if self.timing_flag else "Stop"
        """
        self.ids.start_stop_button_id.text = "开始计时" if self.timing_flag else "停止计时"
        self.timing_flag = not self.timing_flag

    # 重置计时
    def reset_clock(self):
        if self.timing_flag:
            self.ids.start_stop_button_id.text = "开始计时"
            self.ids.stopwatch.text = "00:00.[size=40]00[/size]"
            self.timing_flag = False
        else:
            self.ids.stopwatch.text = "00:00.[size=40]00[/size]"
        self.timing_second = 0


# 继承App类
class ClockApp(App):
    def build(self):
        self.title = "计时器 V 1.0"
        # 返回根控件
        return ClockBoxLayout()


if __name__ == "__main__":  # 程序入口
    from kivy.core.window import Window

    # 设置页面背景颜色
    Window.clearcolor = [0.8, 0.8, 0.8, 1]
    ClockApp().run()  # 启动应用程序
